package ${package}.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ${package}.mapper.SysUserMapper;
import ${package}.service.po.SysUserPO;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
/**
 * 实现oauth2的UserDetailsService，基于数据库查询账号数据
 *
 * @author ${author}
 * @date ${date}
 */
@AllArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户信息
        SysUserPO sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUserPO>().lambda()
                .eq(SysUserPO::getUsername, username));
        if (null == sysUser) {
            throw new UsernameNotFoundException("账号信息不存在！");
        }
        //角色权限
        List<GrantedAuthority> authorityList = new ArrayList<>(AuthorityUtils.createAuthorityList(sysUser.getRole()));
        return new User(sysUser.getUsername(), sysUser.getPassword(), authorityList);
    }
}
